#pragma once
#include <iostream>
#include <vector>
#include <semaphore.h>
#include <pthread.h>

const int N = 5;

template<class T>
class RingQueue
{
private:

    void Lock(pthread_mutex_t& m)
    {
        pthread_mutex_lock(&m);
    }

    void Unlock(pthread_mutex_t& m)
    {
        pthread_mutex_unlock(&m);
    }

public:
    RingQueue(int num = N)
        :_ring(num)
        ,_cap(num)
    {
        sem_init(&_data_sem, 0, 0);
        sem_init(&_space_sem, 0, num);
        _c_step = _p_step = 0;

        pthread_mutex_init(&_c_mutex, nullptr);
        pthread_mutex_init(&_p_mutex, nullptr);
    }

    void push(const T& in)
    {
        sem_wait(&_space_sem);      // P操作
        Lock(_p_mutex);             // 先等待信号量，再加锁，可以提高效率
        _ring[_p_step++] = in;
        _p_step %= _cap;
        Unlock(_p_mutex);
        sem_post(&_data_sem);       // V操作
    }

    void pop(T* out)
    {
        sem_wait(&_data_sem);       // P操作
        Lock(_c_mutex);
        *out = _ring[_c_step++];
        _c_step %= _cap;
        Unlock(_c_mutex);
        sem_post(&_space_sem);      // V操作
    }

    ~RingQueue()
    {
        sem_destroy(&_data_sem);
        sem_destroy(&_space_sem);

        pthread_mutex_destroy(&_c_mutex);
        pthread_mutex_destroy(&_p_mutex);
    }
private:
    std::vector<T> _ring;
    int _cap;
    sem_t _data_sem;
    sem_t _space_sem;
    int _c_step;
    int _p_step;
    pthread_mutex_t _c_mutex;
    pthread_mutex_t _p_mutex;
};